import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/Layout.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/index.vue'),
          meta: { title: '首页', requiresAuth: true }
        },
        {
          path: 'user/list',
          name: 'UserList',
          component: () => import('@/views/user/UserList.vue'),
          meta: { title: '用户列表', requiresAuth: true }
        },
        {
          path: '/fresh/list',
          name: 'FreshList',
          component: () => import('@/views/fresh/FreshList.vue'),
          meta: { title: '生鲜管理', requiresAuth: true }
        },
        {
          path: '/storage/list',
          name: 'StorageList',
          component: () => import('@/views/storage/StorageList.vue'),
          meta: { title: '储位管理', requiresAuth: true }
        },
        {
          path: '/promotion/list',
          name: 'PromotionList',
          component: () => import('@/views/promotion/PromotionList.vue'),
          meta: { title: '促销管理', requiresAuth: true }
        },
        {
          path: '/statistics/delivery',
          name: 'DeliveryStatistics',
          component: () => import('@/views/statistics/DeliveryStatistics.vue'),
          meta: { title: '配送统计', requiresAuth: true }
        },
		{
		          path: '/inventory/check',
		          name: 'InventoryCheck',
		          component: () => import('@/views/inventory/InventoryCheck.vue'),
		          meta: { title: '库存盘点', requiresAuth: true }
		},
		{
		  path: '/statistics/delivery',
		  name: 'DeliveryStatistics',
		  component: () => import('@/views/statistics/DeliveryStatistics.vue'),
		  meta: { title: '配送统计', requiresAuth: true }
		},
		{
		  path: '/routeInfo/list',
		  name: 'RouteInfoList',
		  component: () => import('@/views/routeInfo/RouteInfoList.vue'),
		  meta: { title: '运输规划', requiresAuth: false }
		},
		{
		  path: '/siteInfo/list',
		  name: 'SiteInfoList',
		  component: () => import('@/views/siteInfo/SiteInfoList.vue'),
		  meta: { title: '站点管理', requiresAuth: false }
		}
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const user = localStorage.getItem('user')
  
  if (to.meta.requiresAuth) {
    if (!user) {
      next('/login')
    } else {
      next()
    }
  } else {
    if (user && to.path === '/login') {
      next('/dashboard')
    } else {
      next()
    }
  }
})

export default router
